package ru.urfc.portal.rest;

import ru.urfc.portal.managers.ClientManager;
import ru.urfc.portal.model.AssociationKeyWithEmail;
import ru.urfc.portal.security.PortalUserManager;
import ru.urfc.portal.ui.client.Constants;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Stateless
@Produces({MediaType.APPLICATION_XML, MediaType.TEXT_XML, MediaType.APPLICATION_JSON})
@Path(Constants.USER_ASSOCIATIONS)
public class UserAssociationService extends BaseService {
	
	@EJB ClientManager clientManager;
	@EJB PortalUserManager portalUserManager;
	
	
	@POST
	@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)//TODO in one transaction
	public Response associate(AssociationKeyWithEmail associationKey) {
		if (clientManager.associate(associationKey)) {
			final String userEmail = associationKey.getEmail();
			portalUserManager.grantClientAdminRoles(userEmail);
			return Response.noContent().build();
		}
		return Response.ok(INVALID_ASSOCIATION_KEY).build();
	}

}